﻿using Maticsoft.Common;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using ZhiKeDuoServer.BLL;

namespace ZhiKeDuoServer
{
    partial class ZhiKeDuoService : ServiceBase
    {
        //打印队列
        private Queue _PrintTaskQueue = new Queue();
        //加载队列的线程
        private Thread _LoadThread;
        //执行打印的线程
        private Thread _PrintThread;

        #region 服务的参数
        /// <summary>
        /// 一次搜索的最大任务数,默认10个
        /// </summary>
        private int MaxSerchTaskNum = 10;
        /// <summary>
        /// 搜索间隔,默认1秒
        /// </summary>
        private int SerchThreadInterval = 1000;
        /// <summary>
        /// 任务队列最大任务数,默认100
        /// </summary>
        private int _PrintQueueMaxTaskNum = 100;
        /// <summary>
        /// 是否输出日志记录,默认输出
        /// </summary>
        private bool IsWriteDebugLog = true;
        #endregion
        SaleInfo bsaleInfo = new SaleInfo();
        //ZhiKeDuoServer.BLL. menuPrintBll = new POSPrintSvr.BLL.MenuPrintRequest();
        //POSPrintSvr.BLL.CookRooms cookRoomBll = new POSPrintSvr.BLL.CookRooms();
        public ZhiKeDuoService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            BeginSvrThread();
            if (IsWriteDebugLog)
                LogManager.WriteLog("服务日志", "sycService启动成功！" + DateTime.Now.ToLongTimeString());
        }

        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            if (_LoadThread != null)
            {
                _LoadThread.Abort();
                _LoadThread = null;
            }
            if (IsWriteDebugLog)
                LogManager.WriteLog("服务日志", "SycService停止！" + DateTime.Now.ToLongTimeString());
        }
        //暂停
        protected override void OnPause()
        {
            if (_LoadThread != null)
            {
                _LoadThread.Suspend();
            }
            base.OnPause();
        }
        //继续
        protected override void OnContinue()
        {
            if (_LoadThread != null)
            {
                if (_LoadThread.ThreadState == System.Threading.ThreadState.Suspended
                    || _LoadThread.ThreadState == System.Threading.ThreadState.SuspendRequested)
                {
                    _LoadThread.Resume();
                }
            }
            base.OnContinue();
        }
        /// <summary>
        /// 开始服务的主线程
        /// </summary>
        private void BeginSvrThread()
        {
            if (_LoadThread == null)
            {
                _LoadThread = new Thread(DetectionPrintRequest);
                _LoadThread.Start();
            }
            if (_LoadThread != null)
            {
                if (_LoadThread.ThreadState == System.Threading.ThreadState.Suspended
                    || _LoadThread.ThreadState == System.Threading.ThreadState.SuspendRequested)
                {
                    _LoadThread.Resume();
                }
            }
        }
        /// <summary>
        /// 检测待同步请求，并放入队列
        /// </summary>
        private void DetectionPrintRequest()
        {
            
            string api = "http://hat.ohthink.com/sycapi/sync/";

            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                Formatting = Formatting.None
            };
            ZhiKeDuoServer.BLL.ShopInfo bShop = new ZhiKeDuoServer.BLL.ShopInfo();
            ZhiKeDuoServer.Model.ShopInfo mShop = new ZhiKeDuoServer.Model.ShopInfo();
            mShop = bShop.GetModel(1);
            while (true)
            {
                if (_PrintTaskQueue.Count < _PrintQueueMaxTaskNum)
                {
                    try
                    {
                        // 同步会员
                        WebClient wc = new WebClient();
                        ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.MemberInfo> bmem = new ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.MemberInfo>();
                        List<ZhiKeDuoServer.Model.MemberInfo> lsmem = bmem.GetList("syc=0");
                        foreach (ZhiKeDuoServer.Model.MemberInfo item in lsmem)
                        {
                            string json = JsonConvert.SerializeObject(item);
                            wc.PostJson(api + "add/memberinfo/" + mShop.Shop, json);
                            item.syc = 1;
                            bmem.Update(item);
                        }
                        /// 同步订单
                        /// 
                        /// 
                        ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.SaleInfo> bSaleInfo = new ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.SaleInfo>();
                        List<ZhiKeDuoServer.Model.SaleInfo> lsSaleInfo = bSaleInfo.GetList("syc=0");



                        foreach (ZhiKeDuoServer.Model.SaleInfo item in lsSaleInfo)
                        {
                            string json = JsonConvert.SerializeObject(item, setting);
                            wc.PostJson(api + "add/saleinfo/" + mShop.Shop, json);
                            item.syc = 1;
                            bSaleInfo.Update(item);
                        }
                        /// 同步库存

                        ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.InGoods> bInGoods = new ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.InGoods>();
                        List<ZhiKeDuoServer.Model.InGoods> lsInGoods = bInGoods.GetList("syc=0");
                        foreach (ZhiKeDuoServer.Model.InGoods item in lsInGoods)
                        {
                            string json = JsonConvert.SerializeObject(item);
                            wc.PostJson(api + "add/ingoods/" + mShop.Shop, json);
                            item.syc = 1;
                            bInGoods.Update(item);
                        }
                        /// 同步分类
                        ///
                        ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.Category> bCategory = new ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.Category>();
                        List<ZhiKeDuoServer.Model.Category> lsCategory = bCategory.GetList("syc=0");
                        foreach (ZhiKeDuoServer.Model.Category item in lsCategory)
                        {
                            string json = JsonConvert.SerializeObject(item);
                            wc.PostJson(api + "add/category/" + mShop.Shop, json);
                            item.syc = 1;
                            bCategory.Update(item);
                        }
                        //var ds_loadMenus = bsaleInfo.GetList("");//

                        //foreach (var item in ds_loadMenus)
                        //{
                        //    _PrintTaskQueue.Enqueue(item.Id);
                        //}


                    }
                    catch (Exception ex)
                    {
                        LogManager.WriteLog("Error", ex.Message);
                    }


                    //  StartPrintThread();
                }
                Thread.Sleep(SerchThreadInterval);
            }
        }


        /// <summary>
        /// 启动执行打印的线程
        /// </summary>
        private void StartPrintThread()
        {
            _PrintThread = new Thread(ExecuteOperate_PrintBill);
            _PrintThread.Start();
        }
        /// <summary>
        /// 开始分单打印。
        /// </summary>
        private void ExecuteOperate_PrintBill()
        {
            while (_PrintTaskQueue.Count > 0)
            {
                object obj_KeyId = _PrintTaskQueue.Dequeue();
                ExecuteMenuPrint(int.Parse(obj_KeyId.ToString()));
            }
        }
        /// <summary>
        /// 分单同步
        /// </summary>
        /// <param name="KeyId">流水号</param>
        void ExecuteMenuPrint(int KeyId)
        {
            //开始数据同步 待完成
           
        }


    }
}
